package com.itqf.controller;



import com.cxf.utils.DateUtils;
import com.google.gson.Gson;
import com.itqf.entity.*;
import com.itqf.service.*;
import com.itqf.service.impl.*;
import com.itqf.utils.Constants;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@WebServlet(name = "AdminController", value = "/admin/adminCtr")
public class AdminController extends BaseServlet {


    //初始化业务逻辑对象
    private static AdminService adminService = new AdminServiceImpl();
    private static UserService userService = new UserServiceImpl();
    private static OrderService orderService = new OrderServiceImpl();
    private static ProductService productService = new ProductServiceImpl();
    private static TypeService typeService = new TypeServiceImpl();

    //1.管理员登录
    public String login(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        System.out.println("进行管理员用户登录!!!");

        //1.从前端发送的请求中获取参数(username,password)
        String username = request.getParameter("username");
        System.out.println(username);
        String password = request.getParameter("password");
        System.out.println(password);
        //2.调用业务逻辑，进行查询账号是否存在，再判断密码是否正确
        Admin admin = adminService.checkedUser(username);

        //3.将管理员用户信息存入session作用域中
        request.getSession().setAttribute("admin", admin);
        //2.1 用户存在，再进行密码的验证
        if (admin != null) {
            if (admin.getPassword().equals(password)) {
                //密码验证成功
                //跳转至下个页面(后台主页面)
                System.out.println("管理员验证成功，跳转至后台主页面！！！");
                return Constants.FORWARD + "/admin/admin.jsp";
            } else {
                //密码验证失败
                //重新登录
                return Constants.FORWARD + "/admin/login.jsp";
            }
        }
        //用户不存在
        else {
            //重新登录
            return Constants.FORWARD + "/admin/login.jsp";
        }
    }

    //2.管理员用户注销
    public String logOut(HttpServletRequest request, HttpServletResponse response) {
        //1.清空session中的用户数据
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        //2.清空和覆盖cookie中的自动登录信息
        Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //3.注销成功，重定向至登录页面
        request.setAttribute("msg", "注销成功！！！");
        return Constants.FORWARD + "/admin/login.jsp";
    }

    //3.用户管理

    //3.1 会员管理

    /**
     * 展示所有用户信息
     *
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public String getUserList(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        System.out.println("展示所有管理员信息");
        //1..调用业务逻辑进行查询所有用户信息
        List<User> userList = userService.selectAllUser();
        //3.将用户数据转换为json数据
        Gson gson = new Gson();
        String json = gson.toJson(userList);
        //4.返回json数据给前端页面
        System.out.println(json);
        return json;
    }

    /**
     * 按条件查询用户信息
     *
     * @param request
     * @param response
     * @return
     * @throws SQLException
     * @throws UnsupportedEncodingException
     */
    public String getUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, UnsupportedEncodingException {
        //1.获取前端发送的参数
        String username = request.getParameter("username");
        System.out.println("用户名" + username);
        String usex = request.getParameter("gender");
        System.out.println("性别" + usex);
        System.out.println("该管理员信息");
        //1..调用业务逻辑进行查询所有用户信息
        User user = userService.selectUser(username, usex);
        //3.将用户数据转换为json数据
        Gson gson = new Gson();
        String json = gson.toJson(user);
        //4.返回json数据给前端页面
        System.out.println("json" + json);
        return json;
    }

    //3.2 删除用户信息
    public String deleteUser(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        //1.获取前端发送的参数（uid）
        int uid = Integer.valueOf(request.getParameter("uid"));
        System.out.println(uid + "进行删除用户数据！！！");
        //2.调用业务逻辑，根据uid删除用户信息
        int result = userService.deleteUserByUid(uid);

        if (result != 0) {
            System.out.println("执行删除成功！！！");
            //重新查询所有用户信息
            //1..调用业务逻辑进行查询所有用户信息
            List<User> userList = userService.selectAllUser();
            //3.将用户数据转换为json数据
            Gson gson = new Gson();
            String json = gson.toJson(userList);
            //4.返回json数据给前端页面
            System.out.println(json);
            return json;
        } else {
            System.out.println("执行删除失败！！！");
            return null;
        }
    }


    //4.商品管理

    //4.1 展示所有商品信息
    public String showGoods(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, SQLException, InvocationTargetException {
        //1.调用业务逻辑查询所有商品信息
        List<Product> productList = productService.selectAll();

        //2.将集合存储在作用域中
        request.getSession().setAttribute("productList", productList);

        //3.跳转至商品显示页面
        return Constants.FORWARD + "/admin/showGoods.jsp";
    }

    //4.2 添加商品
    public String addGoods(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        //1.获取前端发送过来的参数
        String pname = request.getParameter("name");
        System.out.println("pname" + pname);
        String pubdate = request.getParameter("pubdate");
        System.out.println("pubdate" + pubdate);
        //将日期转换
        Date ptime = DateUtils.strToUdate(pubdate);
        BigDecimal pprice = BigDecimal.valueOf(Double.valueOf(request.getParameter("price")));
        System.out.println(pprice + "pprice");
        int pstate = Integer.valueOf(request.getParameter("star"));
        System.out.println("pstate" + pstate);
        String pimage = request.getParameter("picture");
        Gson gson = new Gson();
        String json = gson.toJson(pimage);
        System.out.println("pimage" + pimage);
        String pinfo = request.getParameter("intro");
        System.out.println("pinfo" + pinfo);
        int tid = Integer.valueOf(request.getParameter("typeid"));
        System.out.println("typeid" + tid);
        //(int tid, String pname, Date ptime, String pimage, int pstate, String pinfo, BigDecimal pprice) {
        Product product = new Product(tid,pname,ptime,pimage,pstate,pinfo,pprice);

        //2.调用业务逻辑增加
        productService.addProduct(product);
        return null;
    }

    public String showGoodsType(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        System.out.println("展示商品类别信息");
        //1.调用业务逻辑查询所有商品类别信息
        List<Type> typeList = typeService.selectAll();
        //2.将集合存储在作用域中
        request.getSession().setAttribute("typeList",typeList);
        System.out.println(typeList);
        //3.跳转至展示
        return Constants.FORWARD+"/admin/showGoodsType.jsp";
    }


    public String showAllOrders(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, SQLException, InvocationTargetException {

        System.out.println("展示所有订单");
        //1.调用业务逻辑查询所有订单
        List<Orders> ordersList = orderService.findAllOrders();

        System.out.println(ordersList);

        //2.将结果集数据存储于作用域中
        request.getSession().setAttribute("ordersList", ordersList);

        //3.跳转至订单展示页面
        return Constants.FORWARD + "/admin/showAllOrder.jsp";
    }

    public String sendOrder(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        System.out.println("修改订单状态");

        //1.获取前端发送的参数（oid订单ID）
        String oid = request.getParameter("oid");
        System.out.println(oid);

        //2.调用业务逻辑，根据oid修改订单状态.(将订单状态由2改为3)
        orderService.changeStateByOid(oid);

        //3.刷新展示页面
        return Constants.FORWARD + "/admin/adminCtr?method=showAllOrders";
    }


    public String searchOrder(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, SQLException, InvocationTargetException {

        System.out.println("根据用户名和订单状态来查询订单信息！！！");
        //1.获取前端发送过来的参数(username,ostate)
        String username = request.getParameter("username");
        System.out.println("获取到的用户名:" + username);
        String ostate = request.getParameter("ostate");
        System.out.println("获取到的订单状态:" + ostate);

        //2.调用业务逻辑，根据用户名和订单状态来查询订单数据信息
        List<Orders> ordersList = orderService.selectOrderByUsernameAndOstate(username, ostate);
        System.out.println("查询的数据:" + ordersList);
        //3.将查询到的数据存储到作用域中
        request.getSession().setAttribute("ordersList", ordersList);

        //4.返回响应给showAll
        return Constants.FORWARD + "/admin/showAllOrder.jsp";
    }

    public String addType(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        System.out.println("执行添加商品类别");
        //1.获取参数
        String tid = request.getParameter("goodsParent");
        System.out.println("tid"+tid);
        String tparentName = request.getParameter("typename");
        System.out.println("tparentName"+tparentName);
        //根据tid查询到tname
        Type type1 = typeService.selectTypeByTid(tid);
        System.out.println(type1);
        String tname = type1.getTname();
        System.out.println(tname);
        Type type = new Type(tname,tparentName);
        //2.调用业务逻辑进行添加
        typeService.addType(type);

        //3.刷新至展示
        return Constants.REDIRECT+"/admin/adminCtrl?method=showGoodsType";
    }
}
